package com.psedu.exam.timedTask;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.psedu.exam.constant.Constants;
import com.psedu.exam.domain.ExamDeptStatus;
import com.psedu.exam.domain.vo.ExamDetailVo;
import com.psedu.exam.mapper.ExamDeptStatusMapper;
import com.psedu.exam.service.IExamDeptStatusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class ExamTask {

    @Autowired
    private ExamDeptStatusMapper examDeptStatusMapper;

    @Scheduled(cron = "0/5 * * * * ?")
    public void examStatusCheck() {
        List<ExamDeptStatus> examDeptStatusList = examDeptStatusMapper.selectList();
        List<ExamDeptStatus> updateStatusDeptStatusList = new ArrayList<>();
        for (ExamDeptStatus deptExam : examDeptStatusList) {
            Date startTime = deptExam.getStartTime();
            Date endTime = deptExam.getEndTime();
            Integer status = deptExam.getStatus();
            Date nowDate = new Date();
            int realStatus = Constants.DEPT_EXAM_WAIT;
            // 获取正式状态
            if(startTime == null || endTime == null) {
                realStatus = Constants.DEPT_EXAM_WAIT;
            } else if(nowDate.after(startTime) && nowDate.before(endTime)) {
                realStatus = Constants.DEPT_EXAM_RUNNING;
            } else if(nowDate.before(startTime)) {
                realStatus = Constants.DEPT_EXAM_WAIT;
            } else if(nowDate.after(endTime)) {
                realStatus = Constants.DEPT_EXAM_END;
            }
            // 状态不符
            if(status != null && realStatus != status) {
                ExamDeptStatus examDeptStatus = new ExamDeptStatus();
                examDeptStatus.setExamDeptStatusId(deptExam.getExamDeptStatusId());
                examDeptStatus.setStatus(realStatus);
                updateStatusDeptStatusList.add(examDeptStatus);
                deptExam.setStatus(realStatus);
            }
        }
        if(CollectionUtil.isNotEmpty(updateStatusDeptStatusList)) {
            examDeptStatusMapper.updateBatchById(updateStatusDeptStatusList);
        }
    }
}
